package com.wdhcr.service.imp;

import com.wdhcr.entity.User;
import com.wdhcr.repository.UserRepository;
import com.wdhcr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;

/*
 * @description: 用户逻辑的service实现类
 * @author: wdhcr
 * @dateTime: 2020/3/8 18:41
 */
@Service
public class UserServiceImp implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User saveUser(User user) {
        //查询数据库是否为空，为空时，说明这是第一个用户，及默认设置为管理员用户
        List<User> all = userRepository.findAll();
        if (all.isEmpty()){
            //设置权限关键字
            user.setRole("admin");
        }  

        User byOpenid = userRepository.findByOpenid(user.getOpenid());
        if (byOpenid == null){
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            return userRepository.save(user);
        }
        //如果已经保存就将该对象返回
        return byOpenid;

    }

    @Override
    public User findByOpenid(String openid) {
        return userRepository.findByOpenid(openid);
    }

    @Override
    public Set<String> findOpenidAll() {
        return userRepository.findOpenidAll();
    }

    @Override
    public User findById(Integer id) {
        return userRepository.findById(id.longValue()).get();
    }
}
